﻿<?php
/**
 * MVM_MALL 网上商店系统
 * ============================================================================
 * 版权所有 (C) 2007-2010 www.mvmmall.com，并保留所有权利。
 * 网站地址: http://www.mvmmall.com
 * ----------------------------------------------------------------------------
 * 这是一个免费开源的软件；这意味着您可以在不用于商业目的的前提下对程序代码
 * 进行修改、使用和再发布。
 * ============================================================================
 * 
 * @author :     www.mvmmall.com <admin@mvmmall.com> 
 * @version :    v4.X
---------------------------------------------
 */
if(!defined('MVMMALL')){
    exit('Access Denied');
}
//插件的代码必须和文件名保持一致
$payment['alipay']['name']    = '支付宝直接支付';
//描述
$payment['alipay']['desc']    = '使用支付宝直接支付,省去中间复杂确认流程.适合信任商家收款.';

//支付费用
$payment['alipay']['pay_fee'] = '1%';

// 是否支持在线支付
$spayment['alipay']['online']  = 1;

//否支持货到付款
$payment['alipay']['cod']     = 0;

//申请地址
$payment['alipay']['reg']     = 'https://www.alipay.com/user/reg_select.htm';

//版权信息
$payment['alipay']['license']  = '版权所有www.mvmmall.com';

//接口需要的参数
$payment['alipay']['cfg'] =array(
        array('name' => 'seller_email', 'value' => '','label'=>'卖家邮箱'),
        array('name' => 'security_code', 'value' => '','label'=>'支付密钥'),
        array('name' => 'partner', 'value' => '','label'=>'合作伙伴ID'),
    );
    
class alipay
{
    var $cfg;
    function alipay($cfg = array())
    {
        foreach ($cfg AS $key=>$val)
        {
            $this->cfg[$val['name']] = $val['value'];
        }
    }
    
/*提交支付请求*/
function pay_send($sn,$amount)	{
    $partner = $this->cfg[partner];//合作伙伴ID
    $security_code = $this->cfg[security_code];//安全检验码
    $seller_email = $this->cfg[seller_email];//卖家邮箱
    $_input_charset = "utf-8"; //字符编码格式
    $sign_type = "MD5"; //加密方式
    $transport= "http";//访问模式,你可以根据自己的服务器是否支持ssl访问而选择http以及https访问模式
    $notify_url = "";// 异步返回地址
    $return_url = "$GLOBALS[mm_mall_url]$GLOBALS[mm_mall_install_dir]/respond.php?code=".basename(__FILE__, '.class.php');; //同步返回地址
    $parameter = array(
    "service" => "create_direct_pay_by_user", //交易类型，必填实物交易＝trade_create_by_buyer（需要填写物流） 虚拟物品交易＝create_digital_goods_trade_p 捐赠＝create_donate_trade_p
    "partner" =>$partner,                                               //合作商户号
    "return_url" =>$return_url,  //同步返回
    "notify_url" =>$notify_url,  //异步返回
    "_input_charset" => $_input_charset,                                //字符集，默认为GBK
    "subject" => "$sn",                                                //商品名称，必填
    "body" => "",                                           //商品描述，必填
    "out_trade_no" => $sn ,                      //商品外部交易号，必填,每次测试都须修改
    "price" => "$amount",                                 //商品单价，必填
    "discount"=>"",                                    //折扣
    "payment_type"=>"1",                               // 商品支付类型 1 ＝商品购买 2＝服务购买 3＝网络拍卖 4＝捐赠 5＝邮费补偿 6＝奖金
    "quantity" => "1",                                 //商品数量，必填
    "show_url" => "$GLOBALS[mm_mall_url]",            //商品相关网站
    "logistics_type"=>"EXPRESS",                  //物流类型：VIRTUAL＝虚拟物品 POST＝平邮 EMS＝EMS EXPRESS＝其他快递公司
    "logistics_fee"=>"0",                          //物流费用
    "logistics_payment"=>"SELLER_PAY",                //物流支付类型: SELLER_PAY=卖家支付 BUYER_PAY=买家支付 BUYER_PAY_AFTER_RECEIVE=货到付款
    "seller_email" => $seller_email,                //卖家邮箱，必填

    );
    $alipay = new alipay_service($parameter,$security_code,$sign_type);
    $link=$alipay->create_url();
    $result='<a href='.$link.' target="_blank" ><img src="images/pay/alipay.gif"></a>';
    return   $result;
}
    /**
     * 提交返回处理*
     */
    function pay_receive()
    {
        $billno=trim($_REQUEST['out_trade_no']);//定单
        $amount = trim($_REQUEST['total_fee']);//金额
        $security_code = $this->cfg[security_code];//安全检验码
        ksort($_GET);
        reset($_GET);
        $sign = '';
        foreach ($_GET AS $key=>$val){
            if ($key != 'sign' && $key != 'sign_type' && $key != 'code'){
                $sign .= "$key=$val&";
            }
        }
        $sign = substr($sign, 0, -1) .$security_code;
        if (md5($sign) != $_GET['sign']){
            return false;
        }
        if ($_GET['trade_status'] == 'WAIT_SELLER_SEND_GOODS'){
               /*
                #商户网站逻辑处理#
                */
                //比较返回的订单号和金额与数据库中的金额是否相符
                $orderid= strip_tags($billno);
                $list = order_info($orderid);
                if ($list[order_amount]==$amount){
                    /* 改变订单状态*/
                    change_order($orderid);
                    return true;
                }else {
                    //和定单数据库不一致
                    return false;
                }
        }else {
            return false;
        }
    }
}
//支付宝外部服务接口控制
class alipay_service {
	var $gateway = "https://www.alipay.com/cooperate/gateway.do?";         //支付接口
	var $parameter;       //全部需要传递的参数
	var $security_code;  	//安全校验码
	var $mysign;             //签名
	//构造支付宝外部服务接口控制
	function alipay_service($parameter,$security_code,$sign_type = "MD5",$transport= "https") {
		$this->parameter      = $this->para_filter($parameter);
		$this->security_code  = $security_code;
		$this->sign_type      = $sign_type;
		$this->mysign         = '';
		$this->transport      = $transport;
		if($parameter['_input_charset'] == "")
		$this->parameter['_input_charset']='GBK';
		if($this->transport == "https") {
			$this->gateway = "https://www.alipay.com/cooperate/gateway.do?";
		} else $this->gateway = "http://www.alipay.com/cooperate/gateway.do?";
		$sort_array = array();
		$arg = "";
		$sort_array = $this->arg_sort($this->parameter);
		while (list ($key, $val) = each ($sort_array)) {
			$arg.=$key."=".$this->charset_encode($val,$this->parameter['_input_charset'])."&";
		}
		$prestr = substr($arg,0,count($arg)-2);  //去掉最后一个问号
		$this->mysign = $this->sign($prestr.$this->security_code);
	}


	function create_url() {
		$url = $this->gateway;
		$sort_array = array();
		$arg = "";
		$sort_array = $this->arg_sort($this->parameter);
		while (list ($key, $val) = each ($sort_array)) {
			$arg.=$key."=".urlencode($this->charset_encode($val,$this->parameter['_input_charset']))."&";
		}
		$url.= $arg."sign=" .$this->mysign ."&sign_type=".$this->sign_type;
		return $url;

	}

	function arg_sort($array) {
		ksort($array);
		reset($array);
		return $array;

	}

	function sign($prestr) {
		$mysign = "";
		if($this->sign_type == 'MD5') {
			$mysign = md5($prestr);
		}elseif($this->sign_type =='DSA') {
			//DSA 签名方法待后续开发
			die("DSA 签名方法待后续开发，请先使用MD5签名方式");
		}else {
			die("支付宝暂不支持".$this->sign_type."类型的签名方式");
		}
		return $mysign;

	}
	function para_filter($parameter) { //除去数组中的空值和签名模式
		$para = array();
		while (list ($key, $val) = each ($parameter)) {
			if($key == "sign" || $key == "sign_type" || $val == "")continue;
			else	$para[$key] = $parameter[$key];

		}
		return $para;
	}
	//实现多种字符编码方式
	function charset_encode($input,$_output_charset ,$_input_charset ="GBK" ) {
		$output = "";
		if(!isset($_output_charset) )$_output_charset  = $this->parameter['_input_charset '];
		if($_input_charset == $_output_charset || $input ==null) {
			$output = $input;
		} elseif (function_exists("mb_convert_encoding")){
			$output = mb_convert_encoding($input,$_output_charset,$_input_charset);
		} elseif(function_exists("iconv")) {
			$output = iconv($_input_charset,$_output_charset,$input);
		} else die("sorry, you have no libs support for charset change.");
		return $output;
	}
}